/**
 * 
 */
package com.freecsim.sas;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.commons.configuration.PropertyConverter;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.log4j.PropertyConfigurator;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * @author GeorgeWu
 *
 */
public class Stop {
	
	private static final Logger logger = Logger.getLogger(Stop.class.getName());
	/**
	 * @param args
	 */
	public static void main(String[] args){
		try{
		String appHome = System.getProperty("app.home");
		if(appHome == null){
			appHome = ".";
			System.setProperty("app.home", appHome);
		}
		PropertyConfigurator.configure (appHome + File.separator + "conf" + File.separator +  "log4j.properties") ;
		FileReader fr = new FileReader(appHome + File.separator + "conf" + File.separator + "server.xml");
		XMLConfiguration config = new XMLConfiguration();
		config.setFile(new File(appHome + File.separator + "conf" + File.separator + "server.xml"));
		//config.setValidating(true);
		config.load();
		
		Document doc = config.getDocument();
		Element root = doc.getDocumentElement();
		String shutdownPort = root.getAttribute("port");
		String shutdownCommand = root.getAttribute("shutdown");
		
		Socket socket = null;
		PrintStream out = null;
		try {
			socket = new Socket(InetAddress.getByName(null), PropertyConverter.toInteger(shutdownPort));
			out = new PrintStream(socket.getOutputStream());
			out.println(shutdownCommand.trim());
		}catch (IOException e) {
			logger.log(Level.SEVERE, "The port of shutdown is not listen on. " + shutdownPort);
		} finally {
			if (socket != null) {
				socket.close();
			}
			if (out != null){
				out.close();
			}
		}
		}catch (Exception e) {
			logger.log(Level.SEVERE, e.getMessage());
		}
	}
}
